<?php
namespace WebApper\Shortcode;

/*
 * [task_box id='taskBox']
 *
 */
class TaskBox extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'task_box';
	protected $defaults = array(
		'id' => null,		// The unique ID to use for the shortcode. Default: none. Required.
		'tableclasses' => 'table-bordered,table-striped,table-hover,table-condensed',  // Adjusts how the indextable will display. Default: 'table-bordered,table-striped,table-hover,table-condensed'.
		'widget' => false	// Whether to display the Tasks as a page widget
	);

    /**
     * Handles the shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;

		// Clear any 'task' notifications for this user
			global $current_user;
			get_currentuserinfo();
			web_apper_delete_notifications_by_type( $current_user->ID, 'task' );
				
		// Build the shortcode output hrml string
			?>
            <table id="<?php echo $id; ?>_datatable" class="table <?php echo str_replace(",", " ", $tableclasses); ?>">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Subject</th>
                        <?php if ( !$widget ) : ?>
                            <th>Description</th>
                            <th>Status</th>
                        <?php endif; ?>
                        <th>Due</th>
                        <?php if ( !$widget ) : ?>
							<?php if ( !is_page('taskbox') ) : ?>
                                <th>Asigned to</th>
                            <?php else : ?>
                                <th>Record</th>
                            <?php endif; ?>
                            <th>Last updated</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                <?php
                    global $webapper, $wpdb, $current_user;
					get_currentuserinfo();

                    if ( is_page('taskbox') || is_page('dashboard') ) :
						$tasks = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$webapper->tables->tasks} WHERE user_id = %d AND status != %s AND status != %s", $current_user->ID, 'complete', 'archived') );
                    else :
						$tasks = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$webapper->tables->tasks} WHERE post_id = %d", $_GET['postID'] ) );
					endif;
					foreach ( $tasks as $task ) :
                        $user = get_user_by( 'id', $task->user_id );
						$post = get_post( $task->post_id );
						$date = new \DateTime( $task->edited_on );
						$edited_on = $date->getTimestamp();

                        echo '<tr id="' . $task->ID . '">';
                        echo '	<td>' . $task->ID . '</td>';
                        echo '	<td>' . $task->subject . '</td>';
						if ( !$widget ) :
							echo '	<td>' . $task->description . '</td>';
							echo '	<td>' . $task->status . '</td>';
						endif;
                        echo '	<td>' . date('F jS h:i A Y', $task->due) . '</td>';
                        if ( !$widget ) :
							if ( !is_page('taskbox') ) :
								echo '	<td id="' . $task->user_id . '">' . $user->display_name . '</td>';
							else :
								if ( $task->post_id != 0 ) :
									echo '	<td class="linked-field" data-post-id="' . $task->post_id . '">' . $post->post_title . '</td>';
								else :
									echo '	<td></td>';
								endif;
							endif;
							echo '	<td>' . date('F jS h:i A Y', $edited_on) . '</td>';
						endif;
                        echo '</tr>';
                    endforeach;
                ?>
                </tbody>
            </table>

            <?php if ( !$widget ) : ?>
                <form name="<?php echo $id; ?>" id="<?php echo $id; ?>" action="" method="post" class="form-horizontal" novalidate>
                    <input type="hidden" name="action" value="web_apper<?php echo $this->shortcode; ?>" />
                    <input type="hidden" name="web_apper_nonce" value="<?php echo wp_create_nonce( 'WebApperAwesomeness!87' ); ?>" />
                    <input type="hidden" name="web_apper_task" value="add" />
                    <input type="hidden" name="web_apper_id" value="<?php echo $_GET['postID'] ?>" />
                    <input type="hidden" name="web_apper_task_id" value="" />
                    <div id="<?php echo $id; ?>Modal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="<?php echo $id; ?>ModalLabel" aria-hidden="false">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="<?php echo $id; ?>ModalLabel">New</h3>
                        </div>
                        <div class="modal-body">
                            <div id="archiveWarning" style="display: none;"><span class="label label-important pull-left">Archive lead</span><p>&nbsp;You are about to archive a task. Are you sure you want to do this?</p></div>
                            <div class="control-group">
                                <label class="control-label" for="task_template"><strong>Task template:</strong></label>
                                <div class="controls">
                                    <select name="task_template">
                                        <option value="custom">custom</option>
                                        <?php
                                            // Get Task template from Database
                                            global $wpdb, $webapper;
                                            $task_templates = $wpdb->get_results( "SELECT * FROM {$webapper->tables->taskTemplates}" );
                                            foreach ( $task_templates as $template ) :
                                                echo stripslashes("<option data-subject=\"$template->subject\" data-description=\"$template->description\" data-due_in=\"$template->due_in\" data-due_unit=\"$template->due_unit\" data-assign_to_user_type=\"$template->assign_to_user_type\" data-assign_to=\"$template->assign_to\" data-status=\"$template->status\">$template->name</option>");
                                            endforeach;
                                        ?>	
                                    </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label" for="subject"><strong>Subject:</strong></label>
                                <div class="controls">
                                    <input type="text" name="subject">
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label" for="description"><strong>Description:</strong></label>
                                <div class="controls">
                                    <?php
                                    $settings = array(
                                        'wpautop' => false,
                                        'media_buttons' => false,
                                        'textarea_name' => 'description',
                                        'textarea_rows' => 8,
                                        'tinymce' => array (
                                            'theme_advanced_buttons1' => 'formatselect,|,bold,italic,underline,|,bullist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,spellchecker,wp_fullscreen,wp_adv'
                                        )
                                    );
                                    wp_editor( '', 'description', $settings , array( 'quicktags' => false ) );
                                    ?>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label"><strong>Due</strong></label>
                                <div class="controls">
                                    <label class="radio inline"><input type="radio" name="due" value="due_in" checked> In </label>
                                    <label class="radio inline"><input type="radio" name="due" value="due_on"> On</label>
                                </div>
                            </div>
                            <div class="control-group" id="due_in">
                                <label class="control-label" for="due_in"><strong>Due in:</strong></label>
                                <div class="controls">
                                    <input type="number" name="due_in" class="span1" value="1">
                                    <select name="due_in_unit" class="span2">
                                        <option value="hours">hours</option>
                                        <option value="days">days</option>
                                        <option value="weeks">weeks</option>
                                        <option value="months">months</option>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group" id="due_on">
                                <label class="control-label"><strong>Due on:</strong></label>
                                <div class="controls">
                                    <input type="date" name="due_on_date" class="span2">
                                    <select name="due_on_hour" class="span1">
                                        <option></option>
                                        <?php for ( $i = 1; $i <= 12; $i++ ) echo '<option value="' . $i . '">' . $i . '</option>'; ?>
                                    </select>
                                    <select name="due_on_ap_pm" class="span1">
                                        <option value="am">am</option>
                                        <option value="pm">pm</option>
                                    </select>
                                </div>
                            </div>
                            <?php if ( !is_page('taskbox') ) : ?>
                            <div class="control-group">
                                <label class="control-label" for="assign_to_role"><strong>Assign to:</strong></label>
                                <div class="controls">
                                    <select name="assign_to" class="span2">
                                        <option value="rotate_users">rotate users</option>
                                        <?php
                                            $users = get_users( array('role' => 'staff') );
                                            foreach ( $users as $user ) :
                                                echo '<option value="' . $user->data->ID . '">' . $user->data->display_name . '</option>';
                                            endforeach;
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <?php endif; ?>
                            <div class="control-group">
                                <label class="control-label" for="status"><strong>Task status:</strong></label>
                                <div class="controls">
                                    <select name="status">
                                        <option value="assigned">assigned</option>
                                        <option value="in-progress">in-progress</option>
                                        <option value="complete">complete</option>
                                        <option value="archived">archived</option>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label"><strong>Last Updated:</strong></label>
                                <div class="controls">
                                    <input type="text">
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button id="<?php echo $id; ?>_close" class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                            <input type="submit" value="Save" name="" id="save" data-loading-text="Saving..." class="btn btn-primary"><input type="submit" value="Update" name="" id="update" data-loading-text="Updating..." class="btn btn-primary"><input type="submit" value="Archive" name="" id="archive" class="btn btn-danger btn btn-primary" data-loading-text="Deleting...">
                        </div>
                    </div>
                </form>
    
                <!-- Info Modal -->
                <div id="infoModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h3 id="infoModalLabel">Heads Up!</h3>
                    </div>
                    <div class="modal-body">
                        <div id="archiveWarning" style="display: block;">
                            <p><span class="label label-info">Info</span>&nbsp;Please select a row first. To do so, simply click on the row you would like to change.</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                    </div>
                </div>
            <?php endif; ?>

            <script type="text/javascript">
				// Store Commonly manipulated DOM nodes as objects
				nForm = jQuery('#<?php echo $id; ?>');
				nFormTask = jQuery('input[name="web_apper_task"]', nForm);
				nModal = jQuery('.modal', nForm);
				nModalHeader = jQuery('.modal-header h3', nModal)
				nModalBody = jQuery('.modal-body', nModal);
				nModalClose = jQuery('.modal-footer [data-dismiss="modal"]', nModal)
				nModalSaveBtn = jQuery('.modal-footer #save', nModal)
				nModalUpdateBtn = jQuery('.modal-footer #update', nModal)
				nModalArchiveBtn = jQuery('.modal-footer #archive', nModal)
				nModalElements = jQuery('.modal-body>*', nModal);
				nArchiveWarning = jQuery('#archiveWarning', nModal);
				nTaskTable = jQuery('#<?php echo $id; ?>_datatable');
				nRowAlert = jQuery('#infoModal');

				jQuery(document).ready(function($) {

					oTaskTable = $(nTaskTable).dataTable({
						<?php
							if ( !$widget ) :
								// Build the sDom parameter for dataTables
								if( $editor == 'true' )
									$E = 'E';
								global $template;
								if ( stristr($template, 'fullwidth') ) :
									$spanA = 6; $spanB = 6;
								else :
									$spanA = 4; $spanB = 5;
								endif;
								echo "'sDom': \"<'row'<'span".$spanA."'<'editorBtns btn-group'>C><'span".$spanB."'fl>r>t<'row'<'span".$spanA."'i><'span".$spanB."'p>>\",\n";
							else :
								echo "'sDom': \"<'row'r>t<'row'<'span6'p>>\",";
							endif;
						?>
						'sPaginationType': 'bootstrap',
						'oLanguage': {
							'sLengthMenu': 'records per page <select>'+
							'<option value="10">10</option>'+
							'<option value="20">20</option>'+
							'<option value="30">30</option>'+
							'<option value="40">40</option>'+
							'<option value="50">50</option>'+
							'<option value="100">100</option>'+
							'</select>'
						},
						'aoColumnDefs': [ { 'bVisible': false, 'aTargets': [ 0 ] } ],
						'oColVis': {
							'buttonText': 'Columns',
							'bRestore': true,
							'sAlign': 'left',
							'sSize': 'css',
							'aiExclude': [ 0 ]
						},
					});
					
					$('.btn-group').attr('id', 'editorBtns').html('<button id="add_<?php echo $id; ?>_datatable" class="btn  btn-primary">New</button><button id="edit_<?php echo $id; ?>_datatable" class="btn  btn-primary">Edit</button><button id="archive_<?php echo $id; ?>_datatable" class="btn  btn-primary">Archive</button>');
	
					// Add a click handler to the table rows - Sets selected row class
					oTaskTable.on("click", "tr", function( e ) {
						if ( $('td', this).hasClass('dataTables_empty') )
							return;
						if ( $(this).hasClass('row_selected') ) {
							$(this).removeClass('row_selected');
						} else {
							oTaskTable.$('tr.row_selected').removeClass('row_selected');
							$(this).addClass('row_selected');
						}
					});

					// Add a click handler to the linked cells
					oTaskTable.on('hover', "tbody td.linked-field", function( e ) {
						if ( $(this).data('post-id') ) {
							var contents = $(this).html();
							contents = '<a href="<?php echo site_url('singleview-shortcode') . '/?postID='; ?>' + $(this).data('post-id') + '">' + contents + '</a>';
							$(this).html( contents ); 
						}
					});

					// Add a click handler for the Editor Add row button
					$('#add_<?php echo $id; ?>_datatable').on("click", function() {
						$('.alert').remove();  // Close any alerts that may be open
						nForm.resetForm();  // Clear form values
						nFormTask.val('add');  // Set value of hidden form field to desired action
						nModalHeader.html('New');  // Change the modal header
						nModalElements.css('display', 'block');  // Show all elements in the modal body, &
						  nArchiveWarning.css('display', 'none');  // hide the archive warning.
						$('div#due_on').fadeOut(400, function() {
							$('div#due_in').fadeIn(400);
						});
						//nModalClose.html('Cancel');  // Relabel modal close button
						nModalSaveBtn.css('display', 'inline-block');  // Show the Save button, &
						  nModalUpdateBtn.css('display', 'none');  // hide the Update button, &
						  nModalArchiveBtn.css('display', 'none');  // hide the Archive button.
						nModal.modal({ keyboard: false });  // Show the modal
					});
	
					// Add a click handler for the Editor Edit row button
					$('#edit_<?php echo $id; ?>_datatable').on("click", function() {
						if ( $('tr.row_selected').length === 0 ) {
							nRowAlert.modal({ keyboard: false });  // Show modal to alert user no row is selected
							return false;
						}
						$('.alert').remove();  // Close any alerts that may be open
						nForm.resetForm();  // Clear form values
						nFormTask.val('update');  // Set value of hidden form field to desired action
						nModalHeader.html('Update Task');  // Change the modal header
						nModalElements.css('display', 'inline-block');  // Show all elements in the modal body, &
							nArchiveWarning.css('display', 'none');  // hide the archive warning.
						var nTr = $('tr.row_selected');
						
						
						
						
						$('[name="web_apper_task"]').val( 'update' );
						$('[name="web_apper_task_id"]').val( $(nTr).attr('id') );
						$('[name="subject"]').val( $('td:nth-child(1)', nTr).html() );
						$('[name="description"]').val( $('td:nth-child(2)', nTr).html() );
						$('[name="status"]').val( $('td:nth-child(3)', nTr).html() );
						$('[name="submitTask"]').val( 'Update task' );
						
						
						
						
						
						
						
						
						$('div#due_on').fadeOut(400, function() {
							$('div#due_in').fadeIn(400);
						});
						nModalUpdateBtn.css('display', 'inline-block');  // Show the Save button, &
						  nModalSaveBtn.css('display', 'none');  // hide the Update button, &
						  nModalArchiveBtn.css('display', 'none');  // hide the Archive button.
						nModal.modal({ keyboard: false });  // Show the modal
					});
	
					// Add a click handler for the Editor Archive row button 
					$('#archive_<?php echo $id; ?>_datatable').on("click", function() {
						if ( $('tr.row_selected').length === 0 ) {
							nRowAlert.modal({ keyboard: false });  // Show modal to alert user no row is selected
							return false;
						}
						$('.alert').remove();  // Close any alerts that may be open
						nForm.resetForm();  // Clear form values
						var nTr = $('tr.row_selected');
						$('[name="web_apper_task_id"]').val( $(nTr).attr('id') );
						nFormTask.val('archive');  // Set value of hidden form field to desired action
						nModalHeader.html('Archive Task');  // Change the modal header
						nModalElements.css('display', 'none');  // Hide all elements in the modal body, &
							nArchiveWarning.css('display', 'block');  // show the archive warning.
						nModalArchiveBtn.css('display', 'inline-block');  // Show the Save button, &
						  nModalSaveBtn.css('display', 'none');  // hide the Archive button.
						  nModalUpdateBtn.css('display', 'none');  // hide the Update button, &
						nModal.modal({ keyboard: false });  // Show the modal
					});

					$('form#<?php echo $id; ?>').bind("submit", function() {
						$('.alert').remove();  // Close any alerts that may be open
						$.ajax({
							url: "<?php echo site_url('wp-admin/admin-ajax.php'); ?>",
							type: "post",
							data: $("form#<?php echo $id; ?>").serialize(),
							success: function(response) {
								var result = $.parseJSON(response);  // Parse response
								if ( result.success ) {  // If ajax returns a successful save
									if ( result.task == 'add' ) {  // If we added a row
										<?php if ( !is_page('taskbox') ) : ?>
											var oRow = oTaskTable.fnAddDataAndDisplay([result.ID, result.data.subject, result.data.description, result.data.status, result.data.due, result.data.user_name, result.data.edited_on]);  // Add row to table
										<?php else : ?>
											var oRow = oTaskTable.fnAddDataAndDisplay([result.ID, result.data.subject, result.data.description, result.data.status, result.data.due, result.data.record_name, result.data.edited_on]);  // Add row to table
											var nTr = jQuery(oRow.nTr); // Get the row that was added,
											var nTd = oTaskTable.fnGetTd( nTr[0], 5 );  // and the visble position of the cell,
											jQuery(nTd).attr( 'id', result.data.due );  // and link the cell to the record.
										<?php endif; ?>
									} else if ( result.task == 'update' ) {  // If we updated a row
										var rowPosition = oTaskTable.fnGetPosition( jQuery('tbody tr.row_selected')[0] );  // Get the position of the currently selected row
									//	oTaskTable.fnUpdate( [result.ID, result.data.subject, result.data.description, result.data.status, result.data.user_name, result.data.due], rowPosition ); // Update the dataTable row
										<?php if ( !is_page('taskbox') ) : ?>
											oTaskTable.fnUpdate( [result.ID, result.data.subject, result.data.description, result.data.status, result.data.due, result.data.user_name, result.data.edited_on], rowPosition ); // Update the dataTable row
										<?php else : ?>
											oTaskTable.fnUpdate( [result.ID, result.data.subject, result.data.description, result.data.status, result.data.due, result.data.record_name, result.data.edited_on], rowPosition ); // Update the dataTable row
										<?php endif; ?>
									} else if ( result.task == 'archive' ) {  // If we archived a row
										nModalArchiveBtn.fadeOut(400);
										var rowPosition = oTaskTable.fnGetPosition( jQuery('tbody tr.row_selected')[0] );  // Get the position of the currently selected row
										oTaskTable.fnDeleteRow( rowPosition );  // Delete the row
									}
								}
								nArchiveWarning.css('display', 'none');  // hide the archive warning.
								nModalBody.prepend(result.htmlalert);  // Show and alert
							}
						});
						return false;
					});
					
					// Set fields when a Task Template is selected
					$('select[name="task_template"]').on('change', function() {
						$('[name="subject"]').val( $(':selected', this).data('subject') );
						$('[name="description"]').val( $(':selected', this).data('description') );
						$('[name="due"][value="due_in"]').prop('checked', true);
						$('div#due_on').fadeOut(400, function() {
							$('div#due_in').fadeIn(400);
						});
						$('[name="due_in"]').val( $(':selected', this).data('due_in') );
						$('[name="due_in_unit"]').val( $(':selected', this).data('due_unit') );
						$('[name="assign_to"]').val( <?php echo $current_user->ID; ?> );
						$('[name="status"]').val( $(':selected', this).data('status') );
					});
					
					// Toggle Due in/on
					$('input[name="due"]').on('change', function() {
						if ( $(this).val() == 'due_in' ) {
							$('div#due_on').fadeOut(400, function() {
								$('div#due_in').fadeIn(400);
							});
						} else {
							$('div#due_in').fadeOut(400, function() {
								$('div#due_on').fadeIn(400);
							});
						}
					});					

				});
			</script>
 
            <?php
	}

    /**
     * Checks if current user has proper privileges
     *
	 * @param string $usercap
     * @since 1.0
     */
	static protected function user_has_cap( $usercap ) {
		if ( current_user_can( $usercap ) ) :
			return true;
		else :
			return false;
		endif;
	}

    /**
     * Handles ajax requests
     *
     * @since 1.0
     */
	function sendAjaxResponse() {
		check_ajax_referer( 'WebApperAwesomeness!87', 'web_apper_nonce' );  // Verify the security nonce
		if ( $_POST['web_apper_task'] == 'add' ) :
			echo json_encode( $this->insert_task() );
		elseif ( $_POST['web_apper_task'] == 'update' ) :
			echo json_encode( $this->update_task() );
		elseif ( $_POST['web_apper_task'] == 'archive' ) :
			echo json_encode( $this->archive_task() );
		endif;
		die();  // Prevents ajax from returning a '0'
	}

    /**
     * Adds a new task
     *
     * @since 1.0
     */
	public function insert_task() {
		global $webapper, $wpdb, $current_user;
		get_currentuserinfo();

		// Get a due timestamp
		$due = web_apper_task_due_timestamp( $_POST['due'], $_POST['due_in'], $_POST['due_in_unit'], $_POST['due_on_date'], $_POST['due_on_ap_pm'], $_POST['due_on_hour']  );

		 // Get a user ID to assign the task to
		if ( isset($_POST['assign_to']) ) :
			if ( is_numeric( $_POST['assign_to'] ) ) :
				$user_id = $_POST['assign_to'];
			else :
				$user_id = web_apper_auto_assign_task( $_POST['assign_to'] );
			endif;
		else :
			$user_id = $current_user->ID;
		endif;
		
		// Save the task
		$result = web_apper_insert_task( $_POST['subject'], $due, $_POST['task_type'], $current_user->ID, $user_id, $_POST['description'], $_POST['status'], $_POST['web_apper_id'] );
		
		// Add a user notification
		$notified = web_apper_add_notification( $_POST['web_apper_id'], 'task', 'New task', 'Long MSG', $user_id, current_time('timestamp') );
				
		// Send an ajax response
		if ( $result && $notified ) :	
			$user = get_user_by( 'id', $user_id );
			$record = get_post( $_POST['web_apper_id'] );
			$task_data = array( 
				'subject' => $_POST['subject'],
				'description' => $_POST['description'],
				'task_type' => $_POST['task_type'],
				'status' => $_POST['status'],
				'due' => date('F jS h:i:s A', $due),
				'edited_on' => date('F jS h:i:s A', current_time('timestamp')),
				'user_name' => $user->display_name,
				'record_name' => $record->post_title,
				'record_id' => $record->ID,
			);
			return $this->sendResponse( 'Task updated.', 'alert-success', 'Hurray!', true, $_POST['web_apper_task_id'], null, $task_data );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Updates a task
     *
     */
	public function update_task() {
		global $webapper, $wpdb, $current_user;
		get_currentuserinfo();

		// Get a due timestamp
		$due = web_apper_task_due_timestamp( $_POST['due'], $_POST['due_in'], $_POST['due_in_unit'], $_POST['due_on_date'], $_POST['due_on_ap_pm'], $_POST['due_on_hour']  );

		 // Get a user ID to assign the task to
		if ( is_numeric( $_POST['assign_to'] ) ) :
			$user_id = $_POST['assign_to'];
		else :
			$user_id = web_apper_auto_assign_task( $_POST['assign_to']);
		endif;
				
		// Save the task
		$result = web_apper_update_task( $_POST['web_apper_task_id'], $_POST['subject'], $due, $_POST['task_type'], $user_id, $_POST['description'], $_POST['status'], $_POST['web_apper_id'] );
		
		// Add a user notification
		$notified = web_apper_add_notification( $_POST['web_apper_id'], 'task', 'Updated task', 'Long MSG', $user_id, current_time('timestamp') );
				
		// Send an ajax response
		if ( $result && $notified ) :	
			$user = get_user_by( 'id', $user_id );
			$record = get_post( $_POST['web_apper_id'] );
			$task_data = array( 
				'subject' => $_POST['subject'],
				'description' => $_POST['description'],
				'task_type' => $_POST['task_type'],
				'status' => $_POST['status'],
				'due' => date('F jS h:i:s A'),
				'user_name' => $user->display_name,
				'record_name' => $record->post_title,
				'record_id' => $record->ID,
			);
			return $this->sendResponse( 'Task updated.', 'alert-success', 'Hurray!', true, $_POST['web_apper_task_id'], null, $task_data );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem saving the task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

    /**
     * Archives a task
     *
     */
	public function archive_task() {
		$result = web_apper_archive_task( $_POST['web_apper_task_id'] );
		if ( $result ) :	
			return $this->sendResponse( 'Task archived.', 'alert-success', 'Hurray!', true, $_POST['web_apper_task_id'] );  // Send Response
		else :
			return $this->sendResponse( 'There was a problem archiving the Task. Please Try again.', 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}

}

$initialize = new TaskBox(); 

?>